package com.xixi.core.rpc.serializer;

import com.xixi.core.rpc.spi.SpiLoader;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: zxh
 * @date: 2024/8/21 23:16
 * @description: 序列化工厂
 */
public class CustomSerializerFactory {

	// 序列化映射，硬编码
	// private static final Map<String, CustomSerializer> KEY_SERIALIZER_MAP =
	// 		new HashMap<String, CustomSerializer>() {{
	// 	put(CustomSerializerKeys.JDK, new CustomJdkSerializer());
	// 	put(CustomSerializerKeys.JSON, new CustomJsonSerializer());
	// 	put(CustomSerializerKeys.KRYO, new CustomKryoSerializer());
	// 	put(CustomSerializerKeys.HESSIAN, new CustomHessianSerializer());
	// }};

	// 使用SPI加载序列化器
	static {
		SpiLoader.load(CustomSerializer.class);
	}

	// 默认序列化器
	// private static final CustomSerializer DEFAULT_SERIALIZER = KEY_SERIALIZER_MAP.get("jdk");
	private static final CustomSerializer DEFAULT_SERIALIZER = new CustomJdkSerializer();

	/**
	 * 获取实例
	 * @param key 序列化器key
	 * @return 返回序列化器实例
	 */
	public static CustomSerializer getInstance(String key) {
		// 硬编码
		// return KEY_SERIALIZER_MAP.getOrDefault(key, DEFAULT_SERIALIZER);
		// 使用SPI
		return SpiLoader.getInstance(CustomSerializer.class, key);
	}
}
